package com.tarim.streetdance.util;

import com.tarim.streetdance.model.FileSystemWithBLOBs;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.web.multipart.MultipartFile;
import sun.awt.HKSCS;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.*;


/**
 * 上传文件工具类
 */
public class UploadFileUtil {

    public static String filePath;

    public static String fileUrl;

    static{
        //服务器用
        filePath = "/data/file/streedance/";
        fileUrl = "http://123.56.87.55/static/streedance/";

        //本地用
        /*filePath = "/Users/l2day/Documents/毕设/任建衡-高校街舞宣传/file/";
        fileUrl = "http://localhost/static/";*/
    }

    //视频类型
    static List<String> videoTypeList = new LinkedList<>();
    static {
        videoTypeList.add("MP4");
        videoTypeList.add("OGG");
        videoTypeList.add("WEBM");

        /*videoTypeList.add("RMVB");
        videoTypeList.add("WMV");
        videoTypeList.add("ASF");
        videoTypeList.add("AVI");
        videoTypeList.add("3GP");
        videoTypeList.add("MKV");
        videoTypeList.add("MOV");
        videoTypeList.add("MPG");
        videoTypeList.add("MPEG");
        videoTypeList.add("MPE");
        videoTypeList.add("FLV");
        videoTypeList.add("F4V");
        videoTypeList.add("M4V");
        videoTypeList.add("QT");
        videoTypeList.add("RM");*/
    }

    //视频类型
    static List<String> imageTypeList = new LinkedList<>();
    static {
        imageTypeList.add("PNG");
        imageTypeList.add("JPG");
        imageTypeList.add("JEPG");
    }

    public static FileSystemWithBLOBs uploadImage(MultipartFile file) throws IOException {
        // 重构文件名称
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!imageTypeList.contains(suffix.toUpperCase())) {
            return null;
        }
        String pikId = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = pikId + "." + suffix;
        File fileSave = new File(filePath, newFileName);
        //判断文件父目录是否存在
        if (!fileSave.getParentFile().exists()) {
            fileSave.getParentFile().mkdirs();
        }
        //保存文件
        file.transferTo(fileSave);
        FileSystemWithBLOBs fileSystemWithBLOBs = new FileSystemWithBLOBs();
        fileSystemWithBLOBs.setId(pikId);
        fileSystemWithBLOBs.setFilename(file.getOriginalFilename());
        fileSystemWithBLOBs.setFilepath(filePath + newFileName);
        fileSystemWithBLOBs.setFilesize(String.valueOf(file.getSize()));
        fileSystemWithBLOBs.setUrl(fileUrl + newFileName);
        fileSystemWithBLOBs.setCreateTime(new Date());
        fileSystemWithBLOBs.setDr(0);
        return fileSystemWithBLOBs;
    }

    public static List<FileSystemWithBLOBs> upload(MultipartFile[] files) throws IOException {
        List<FileSystemWithBLOBs> fileSystems = new ArrayList<>();
        for (MultipartFile file : files){
            // 重构文件名称
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            if (!videoTypeList.contains(suffix.toUpperCase())) {
                return null;
            }
            String pikId = UUID.randomUUID().toString().replaceAll("-", "");
            String newFileName = pikId + "." + suffix;
            File fileSave = new File(filePath, newFileName);
            //判断文件父目录是否存在
            if (!fileSave.getParentFile().exists()) {
                fileSave.getParentFile().mkdirs();
            }
            //保存文件
            file.transferTo(fileSave);
            FileSystemWithBLOBs fileSystemWithBLOBs = new FileSystemWithBLOBs();
            fileSystems.add(fileSystemWithBLOBs);
            fileSystemWithBLOBs.setId(pikId);
            fileSystemWithBLOBs.setFilename(file.getOriginalFilename());
            fileSystemWithBLOBs.setFilepath(filePath + newFileName);
            fileSystemWithBLOBs.setFilesize(String.valueOf(file.getSize()));
            fileSystemWithBLOBs.setUrl(fileUrl + newFileName);
            fileSystemWithBLOBs.setCreateTime(new Date());
            fileSystemWithBLOBs.setDr(0);
        }
        return fileSystems;
    }

    public static synchronized FileSystemWithBLOBs upload(MultipartFile file) throws IOException {
        // 重构文件名称
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!videoTypeList.contains(suffix.toUpperCase())) {
            return null;
        }
        String pikId = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = pikId + "." + suffix;
        File fileSave = new File(filePath, newFileName);
        //判断文件父目录是否存在
        if (!fileSave.getParentFile().exists()) {
            fileSave.getParentFile().mkdirs();
        }
        //保存文件
        file.transferTo(fileSave);
        FileSystemWithBLOBs fileSystemWithBLOBs = new FileSystemWithBLOBs();
        fileSystemWithBLOBs.setId(pikId);
        fileSystemWithBLOBs.setFilename(file.getOriginalFilename());
        fileSystemWithBLOBs.setFilepath(filePath + newFileName);
        fileSystemWithBLOBs.setFilesize(String.valueOf(file.getSize()));
        fileSystemWithBLOBs.setUrl(fileUrl + newFileName);
        fileSystemWithBLOBs.setCreateTime(new Date());
        fileSystemWithBLOBs.setDr(0);
        return fileSystemWithBLOBs;
    }

    public static FileSystemWithBLOBs getTempPath(String videoFilePath) throws Exception {
        String pikId = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = pikId + ".jpg";
        File targetFile = new File(filePath, newFileName);
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        File file2 = new File(videoFilePath);
        if (file2.exists()) {
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file2);
            ff.start();
            int ftp = ff.getLengthInFrames();
            int flag=0;
            Frame frame = null;
            while (flag <= ftp) {
                //获取帧
                frame = ff.grabImage();
                //过滤前3帧，避免出现全黑图片
                if ((flag>3)&&(frame != null)) {
                    break;
                }
                flag++;
            }
            ImageIO.write(FrameToBufferedImage(frame), "jpg", targetFile);
            ff.close();
            ff.stop();
        }
        FileSystemWithBLOBs fileSystemWithBLOBs = new FileSystemWithBLOBs();
        fileSystemWithBLOBs.setId(pikId);
        fileSystemWithBLOBs.setFilename(targetFile.getName());
        fileSystemWithBLOBs.setFilepath(filePath + newFileName);
        fileSystemWithBLOBs.setFilesize(String.valueOf(targetFile.length()));
        fileSystemWithBLOBs.setUrl(fileUrl + newFileName);
        fileSystemWithBLOBs.setCreateTime(new Date());
        fileSystemWithBLOBs.setDr(0);
        return fileSystemWithBLOBs;
    }
    private static RenderedImage FrameToBufferedImage(Frame frame) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        return bufferedImage;
    }

    public static String getImageBase64code(String iamgePath) {
        try {
            File file = new File(iamgePath);
            FileInputStream fs;

            fs = new FileInputStream(file);

            byte[] data = new byte[fs.available()];
            fs.read(data);
            fs.close();
            BASE64Encoder be = new BASE64Encoder();

            return be.encode(data);
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    public static String base64CodeToimage(String basee64code) throws IOException {
        if (basee64code == null) {
            return null;// 图像数据为空
        }
        BASE64Decoder decoder = new BASE64Decoder();
        //byte[] b = decoder.decodeBuffer(basee64code.replace("data:image/jpeg;base64,", ""));//去除base64中无用的部分
        OutputStream out = null;
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = "";
        if (basee64code.indexOf("data:image/png;") != -1) {
            newFileName = id + ".png";
        } else if (basee64code.indexOf("data:image/jpeg;") != -1) {
            newFileName = id + ".jpeg";
        } else if (basee64code.indexOf("data:image/gif;") != -1) {
            newFileName = id + ".gif";
        } else {
            return null;
        }
        try {
            basee64code.replaceAll(" ", "+");
            basee64code = basee64code.substring(basee64code.indexOf(",") + 1);
            out = new FileOutputStream(filePath + newFileName);
            // Base64解码
            byte[] b = decoder.decodeBuffer(basee64code);

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            out.write(b);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
            return newFileName;
        }
    }

}
